$(function (){

	$(".listBox").find('li').eq(sessionStorage.getItem('cacheIndex')).addClass('selected');
	$(".listBox").find('li').click(function (){
		print = [];
		clip = [];
		$(".listBox").find('li').removeClass('selected')
		sessionStorage.setItem('cacheIndex', $(this).index() )
		$(this).addClass('selected')
		let signId = $(this).find(".signId").val();
		realSignid(signId);
	})
	$(".listBox").find('.selected').click();

})

const storeAge = JSON.parse(sessionStorage.getItem('store'));
let objData = {
	court2: storeAge.id,
	current:1,
	number: 50
}, str = '';

ersPages()
function ersPages(){

	$.ajax({
		cache : true,
		type : "post",
		url : '/jzweb/stuSignUpScoring/ersPage',
		data : objData,// 你的formid
		async : false,
		error : function(request) {
			parent.layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {
				if(data.data.records.length){
					$(".fixedList").show();
					data.data.records.map(function (v,k){
						str += `
							<li class="${k == 0 ?'selected':''}">
								<a href="#">${v.num2}</a>
								<input type="hidden" value="${v.id}" class="signId">
								<input type="hidden" value="${v.cbatchId}" class="cbatchId">
								<input type="hidden" value="${v.court}" class="court">
							</li>`;
					});
					$(".listBox").html(str)
					str = '';
				}else{
					$(".fixed-table-toolbar").append('<div style="font-size:16px;text-align: center;margin-top: 50px">暂无数据</div>')
					$(".fixedList").hide();
				}

				layui.use(['laypage', 'layer'], function () {
					var laypage = layui.laypage
						, layer = layui.layer;
					laypage.render({
						elem: 'grid_paging_part'
						, theme: '#1E9FFF'
						, count: data.data.total
						, limit: 50
						, groups: 5
						// ,layout:['count','page','skip']
						, jump: function (obj, first) {
							if (!first) {
								objData.current = obj.curr;
								// ersPages( $('.selected').find(".signId").val() );
								ersPages();
							}
						}
						, curr: objData.current
					});
				})

			} else {
				parent.layer.alert(data.msg)
			}
		}
	});
}

$("body").on('click','.dayFont',function (){
	$(".shade").show();
	$(".fixedner").show();
})

$("#close").click(function (){
	$(".shade").hide();
	$(".fixedner").hide();
})

$(".shadeHide").click(function (){
	$(".shade").hide();
	$(".fixedner").hide();
})

$("#loginInfo").click(function (){
	let obj = {
		userName: $("#username").val() ,
		passWord: $("#password").val()
	}
	$.ajax({
		cache : true,
		type : "post",
		url : '/jzweb/examinationAnswerSheetCom/oneLevelLogin',
		data : obj,// 你的formid
		async : false,
		error : function(request) {
			parent.layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {
				$(".shade").hide();
				$(".fixedner").hide();
				$(".loginData").hide();
				$(".scroller").show().val($(this).text());
				$(this).hide();
				$("#judgeMark").hide();
				$("#amend").show();
				parent.layer.msg("登录成功");
			} else {
				parent.layer.alert(data.msg)
			}
		}
	});
})

function update(url,type,thit) {
	let marrk = $("#score").val();
	layer.open({
		content: '你的打分为'+ marrk
		,btn: ['确定', '取消']
		,yes: function(idx, layero){

			// layer.load();

			const store = JSON.parse(sessionStorage.getItem('store')) , that = thit;
			let obj = []
			// if( type == 1 ){
			// 	$(".userList").each(function (k,v){

			obj.push({
				raceId: store.id,
				competition: sessionStorage.getItem('race'),
				ebatchId: store.ebatchId,
				jinzhuanTopicId: $('.topicId').val(),
				refereeId: sessionStorage.getItem('refereeId'),
				signId: $(".selected").find('.signId').val(),
				score: $(".scroller").find('input').val(),
				cbatchId: store.cbatchId,
				refereeRemark:$("#refereeRemark").val()
			})


			if( obj[0].score == '' ){
				layer.msg('未打分，不能提交');
				return false;
			}

			if( obj[0].score > parseInt( $("#topicScore").val() ) ){
				layer.msg('请勿超过'+ $("#topicScore").val() +'分');
				return false;
			}

			let markDO = {
				markDO: obj
			};


			$.ajax({
				cache : true,
				type : "post",
				url : url,
				data : JSON.stringify(markDO),// 你的formid
				contentType: 'application/json',
				async : false,
				error : function(request) {
					parent.layer.alert("Connection error");
				},
				success : function(data) {
					if (data.code == 0) {
						layer.closeAll();
						layer.msg('打分成功');
						$("#"+that).hide();
						$("#judgeMark").hide();
						$(".scroller").hide();
						$(".loginData").show().find('.dayFont').html(`${$(".scroller").find('input').val()} 修改打分`)
					} else {
						parent.layer.alert(data.msg)
						layer.closeAll();
					}
				}
			});

		}
		,btn2: function(index, layero){
			//按钮【按钮二】的回调
			//return false 开启该代码可禁止点击该按钮关闭
		}
	});

}

function update1(url,type,thit) {
	let marrk = $("#score").val();
	layer.open({
		content: '你的打分为'+ marrk
		,btn: ['确定', '取消']
		,yes: function(idx, layero){

			// layer.load();

			const store = JSON.parse(sessionStorage.getItem('store')) , that = thit;
			let obj = []
			// if( type == 1 ){
			// 	$(".userList").each(function (k,v){

			obj.push({
				raceId: store.id,
				competition: sessionStorage.getItem('race'),
				ebatchId: store.ebatchId,
				jinzhuanTopicId: $('.topicId').val(),
				refereeId: sessionStorage.getItem('refereeId'),
				signId: $(".selected").find('.signId').val(),
				updateScore: $(".scroller").find('input').val(),
				cbatchId: store.cbatchId,
				refereeRemark:$("#refereeRemark").val()
			})


			if( obj[0].updateScore == '' ){
				layer.msg('未打分，不能提交');
				return false;
			}

			if( obj[0].updateScore > parseInt( $("#topicScore").val() ) ){
				layer.msg('请勿超过'+ $("#topicScore").val() +'分');
				return false;
			}

			let markDO = {
				markDO: obj
			};


			$.ajax({
				cache : true,
				type : "post",
				url : url,
				data : JSON.stringify(markDO),// 你的formid
				contentType: 'application/json',
				async : false,
				error : function(request) {
					parent.layer.alert("Connection error");
				},
				success : function(data) {
					if (data.code == 0) {
						layer.closeAll();
						layer.msg('打分成功');
						$("#"+that).hide();
						$("#judgeMark").hide();
						$(".scroller").hide();
						$(".loginData").show().find('.dayFont').html(`${$(".scroller").find('input').val()} 修改打分`)
					} else {
						parent.layer.alert(data.msg)
						layer.closeAll();
					}
				}
			});

		}
		,btn2: function(index, layero){
			//按钮【按钮二】的回调
			//return false 开启该代码可禁止点击该按钮关闭
		}
	});

}

//刷新iframe
function refreshTab() {
	var $pageTabsContent = $('.page-tabs-content');
	$pageTabsContent.children("[data-id]").each(function () {
		if($(this).hasClass('active')==true){
			var target = $('.J_iframe[data-id="' + $(this).data('id') + '"]');
			// console.log("target",target);
			var url = target.attr('src');
			//显示loading提示
			var loading = layer.load();
			target.attr('src', url).load(function () {
				//关闭loading提示
				layer.close(loading);
			});
		}
	});

}

let print = [] , clip = [];
function uploadResoure() {
	layui.use(['upload', 'element', 'layer'], function () {
		var upload = layui.upload;
		let index;
		upload.render({
			elem: '.demoMore'
			, accept: 'file'
			, file: ''
			, choose: function (obj) {
				index = layer.load(1, {fixed: false, offset: 'auto'});
			}
			, done: function (res) {
				layer.close(index);
				if (this.type == '1') {
					print.push(res.data);
					let str = '';
					print.forEach(function (v,k){
						str += `
							<div class="closeBtn" >
								<img class="upImg" src="${v}">
								<span class="iconclose" data-index="${k}" data-comit="1"><img src="../../../img/close.png"></span>
							</div>
						`;
					})
					$(".scoingb1img1").val(print);
					$(".picture").html(str).show();
				}

				if (this.type == '2') {
					clip.push(res.data);
					let str = '';
					clip.forEach(function (v,k){
						str += `
							<div class="closeBtn">
								<video controls autoplay name="media">
									<source src="${v}" type="video/mp4">
								</video>
								<span class="iconclose" data-index="${k}" data-comit="2"><img src="../../../img/close.png"></span>
							</div>
						`;
					})
					$(".scoingb1smp1").val(clip);
					$(".video").html(str).show();
				}

			}
			, error: function (res) {
				layer.close(index);
				layer.msg('上传失败，请检查')
			}
		})
	})
}

$("body").on("click",".upImg",function (){
	$(".shade").show();
	$(".blow").show();
	$(".blow").find('img').attr('src',$(this).attr("src"));
})

$(".shade").click(function (){
	$(this).hide();
	$(".blow").hide();
});

function realSignid(signid){
	const store = JSON.parse( sessionStorage.getItem('store'));
	const delivery = {
		"moduleId": store.modileId,
		"pid": store.ebatchId,
		"raceId": store.id,
		"refereeId": sessionStorage.getItem('refereeId'),
		"signId": signid,
		"userId": sessionStorage.getItem('refereeId'),
		"cbatchId": store.cbatchId
		// "refereeRemark":store.refereeRemark,
	}
	$.ajax({
		cache : true,
		type : "post",
		contentType: "application/json; charset=utf-8",
		url : '/jz-jinzhuan-disposition-module/selectModule',
		data : JSON.stringify(delivery),// 你的formid
		async : false,
		error : function(request) {
			parent.layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {
				let str = '';
				// moduleTopicMarkVo
				const store = JSON.parse(sessionStorage.getItem('store'));
				let totalScore = 0;
				data.data.moduleTopicMarkVo.map(function (v,k){

					$(".rival").html(v.batchName)

					str+=`<div id="topicListBox" style="overflow: hidden;"><div class="subject">${v.topicName}</div><div class="subjectContent">${v.description}</div>`;
					v.isTurr = false;
					// <p>您的打分</p>
					if( k == 0 ) str += `<div class="tableHeader"><p class="module">细则模块</p><p>具体细则</p><p class="scoreBox">分值</p></div>`;
					v.jzJinzhuanModuleContent?.map(function (item,key){
						// console.log(item.score,'fen')
						totalScore += item.score * 1
						str += `
							<div class="userList">
								<div class="description">${item.contentName}</div>
								<div class="rules">
									${item.detailContent}
								</div>
								<div class="scoreBox">${item.contentScore}</div>								
							</div>
						`;
					})
					// if( k == 0 ){
						str += `
						<input value="${v.topicId}" type="hidden" class="topicId">
						<input value="${v.topicScore}" id="topicScore" type="hidden">
						<div class="total">
							<p class="scroller" style="${data.data.refereeScore > 0 ? 'display:none':''}">
								您的打分：<input type="text" placeholder="请在此输入您的打分" id="score">
							</p>
							<p class="loginData" style=" ${data.data.refereeScore > 0 ? '':'display:none'}">您的打分：<span class="dayFont" style="cursor:pointer;">${data.data.refereeScore} 修改打分</span></p>
						</div>
						
						<div class="remark">
							<p>备注：</p>
							<textarea class="form-control" placeholder="请输入你的备注" id="refereeRemark" value="${data.data.refereeRemark || ''}">${data.data.refereeRemark || ''}</textarea>
						</div>
						
						<div class="form-group" id="judgeMark" style="${data.data.refereeScore > 0 ? 'display:none':''}">
							<div class="col-sm-4 col-sm-offset-4">
								<button type="button" onclick="update('/jzweb/mark/judgeMark',1,'judgeMark')" class="btn btn-primary btn-block">提交</button>
							</div>
						</div>
						
						<div class="form-group" style="display: none" id="amend">
							<div class="col-sm-4 col-sm-offset-4">
								<button type="button" onclick="update1('/jzweb/mark/conservatorJudgeMark',2,'amend')" class="btn btn-primary btn-block">提交</button>
							</div>
						</div>
					</div>
					`;
					// }
				})

				$("#topicList").html(str);
				uploadResoure();

			} else {
				parent.layer.alert(data.msg)
			}
		}
	});
}


$("body").on('click','.iconclose',function (){
	let comit = $(this).attr('data-comit');
	$(this).parents(".closeBtn").remove();
	if( comit == 1 ){
		let src = $(this).parents(".closeBtn").find('.upImg').attr('src');
		let smp = $(".scoingb1img1").val();
		if( smp.indexOf(src) != -1 ){
			let arr = smp.split(',');
			arr.splice( arr.findIndex(item => item === src), 1 )
			$(".scoingb1img1").val( arr.join(',') );
			print = arr;
		}
	}else{
		let src = $(this).parents(".closeBtn").find('video source').attr('src');
		let smp = $(".scoingb1smp1").val();
		if( smp.indexOf(src) != -1 ){
			let arr = smp.split(',');
			arr.splice( arr.findIndex(item => item === src), 1 )
			$(".scoingb1smp1").val( arr.join(',') );
			clip = arr;
		}
	}

})
